<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Paykey extends FOX_Controller {

	function __construct ()
	{
        if(!$this->session->userdata('user_id')){
            redirect(site_url('nologin'));
        }
		parent::__construct();
		$this->load->model('smslog_m');
        $this->load->model('credit_m');
        $this->config->load('userset');
        $this->load->model('qqUser_m');
        // if($this->session->userdata('user_id')){
        //     redirect(site_url('member'));
        // }
	}
	/**
     * 发送验证码逻辑
     */
    public function ajax_send_sms()
    {
        $mobile =$this->input->get("mobile");

        if(empty($mobile)){
            echo json_encode(['code'=>400,'msg' => '参数缺失']);exit();
        }
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['code'=>200,'msg' => '号码格式错误']);
            exit;
        }
        // 生成验证码
        $code = $this->creatCodeByRand();
        // 入库
        $data = array(
            'mobile'=>$mobile,
            'yzm'=>$code,
            // 'pay_key'=>$pay_key,
            'type'=>1,
            'createtime'=>date("Y-m-d H:i:s", time()),
        );
        if($this->smslog_m->add_sms_log($data)){
            //发送验证码
            $response = $this->send_sms_code($mobile, $code);
            // 返回
            if (isset($response->Code) && $response->Code == 'OK') {
                // 缓存
                $phoneCode = $this->phoneCodeArr($mobile);
                $phoneCode[$mobile] = ['code'=>$code, 'status'=>0];
                $this->session->set_userdata($mobile.'_info',$phoneCode);
                echo json_encode(['code' => 200, 'msg' => '发送成功']);exit();
            } else {
                echo json_encode(['code' => 400, 'msg' => '发送失败']);exit();
            }
        }else{
            echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);exit();
        }

    }

    /**
     * 短信验证码修改支付密码
     */
    public function sms_pay_key(){
        $user_id = $this->session->userdata('user_id');
        $mobile =$this->input->post("mobile");
        $yzm =$this->input->post("yzm");
        $pay_key =$this->input->post("pay_key");
        // 根据mobile查询数据库
        $sms = $this->smslog_m->get_sms_log_by($mobile,$yzm,0);
        if(!empty($sms)){
            // 验证是否正确
            if (!$this->verifyPhoneCode($mobile, $yzm)) {
                echo json_encode(['code'=>400, 'msg'=>"验证码不正确！"]);
                exit;
            }else{
                // 号码更新为已验证
                $this->smslog_m->sava_sms_log($sms['id'],['is_checked'=>1]);
                $data = array(
                    'user_money_key'=>md5($pay_key),
                        
                    );
                if($this->user_m->update_user($user_id,$data)){
                    echo json_encode(['code' => 200, 'msg' => '设置支付密码成功']);exit();
                    exit;
                }else{
                echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试','code' => $this->security->get_csrf_hash()]);exit();
            }
            }
        }else{
                echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试','code' => $this->security->get_csrf_hash()]);exit();
        }

            // 号码更新为已验证
            // $this->smslog_m->sava_sms_log($sms['id'],['is_checked'=>1]);
            //得到用户的支付密码
    }
    /**
     * 生成验证码
     * @return string
     */
    private function creatCodeByRand(){
        $token = '';
        $len = 6;
        for ($i = 0; $i < $len; $i++)
            $token .= chr(mt_rand(48, 57));
        return $token;
    }
    /**
     * 短信验证码接口
     * @param $mobile 手机号码
     * @param $code 验证码
     * @param string $temp 短信模板
     * @param string $type 模板自定义变量
     * @return stdClass
     */
    public function send_sms_code($mobile, $code,$temp = 'SMS_110605015',$type = 'code') {

        $this->load->library('alisms');
        $response = $this->alisms->sendSms("忠赢科技短信测试", $temp, $mobile, [ $type => $code]);
//        return (object)['Code'=>"OK"];
        return $response;
    }

    /**
     * 验证手机号规则
     * @param $mobile
     * @return bool
     */
    public function verifyMobile($mobile) {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if(preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }

    /**
     * 查询缓存
     * @param $mobile
     * @return array|mixed
     */
    private function phoneCodeArr($mobile) {
        $info = $this->session->userdata($mobile."_info");
        if (!empty($info)) {
            return $info;
        }
        return [];
    }
    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode) {
        $result = false;
        $phoneCodeArr = $this->phoneCodeArr($mobile);
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata($mobile.'_info',$phoneCodeArr);
                $result = true;
            }
        }
        return $result;
    }

    /**
     * 初始化用户密码
     * @param $mobile
     */
    private function init_pwd($mobile){

        $str = substr($mobile,6);
        return md5($str);
    }

}
